<?php

namespace app\system\model;

use think\Model;

class SysAdminModel extends Model
{
    protected $table = "sys_admin";
    protected $pk = "admin_id";

    protected $field = [
        "admin_id",         //主键
        "username",         //用户名
        "pwd",              //密码MD5
        "email",            //邮箱
        "phone",            //手机
        "gender",           //0女，1男
        "state",            //0已禁止，1正常
        "last_login_time",  //最后登陆时间
        "role_id"           //角色id
    ];

    public function getUserListWithPaginate($keyword, $pageSize)
    {
        $where = "";
        if (!empty($keyword)) {
            $where = "username like '%{$keyword}%' or email like '%{$keyword}%' or phone like '%{$keyword}%'";
        }
        $userList = $this->field("a.admin_id,a.username,a.email,a.phone,a.gender,a.state,a.last_login_time,r.role_id,r.r_name")
            ->alias("a")
            ->leftjoin("sys_role r", "r.role_id = a.role_id")
            ->where($where)->order(["a.admin_id" => "desc"])->paginate($pageSize);
        return $userList;
    }

    public function addUserData($data)
    {
        $result = $this->allowField(true)->save($data);
        return $result;
    }

    public function delUserById($admin_id)
    {
        $result = $this->where(["admin_id" => $admin_id])->delete();
        return $result;
    }

    public function updUserData($data, $admin_id)
    {
        $result = $this->allowField(true)->force(true)->save($data, ["admin_id" => $admin_id]);
        return $result;
    }

    public function getUserById($admin_id)
    {
        $user = $this->where(["admin_id" => $admin_id])->find();
        return $user;
    }

    public function getUserByName($username)
    {
        $user = $this->where(["username" => $username])->find();
        return $user;
    }
}
